package qc.module.ehs.service;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import qc.common.core.exception.QCPromptException;
import qc.common.core.unify.QCUnifyReturnValue;
import qc.module.ehs.entity.EhsUnitLateststatus;
import qc.module.ehs.repository.EhsUnitLateststatusRepository;

import java.util.Objects;

/**
 * 单元在最新状态表Service
 *
 * @author QuCheng Tech
 * @create 2024/6/28
 */
@Service
public class EhsUnitLateststatusService {
    
    @Autowired
    private EhsUnitLateststatusRepository repository;

    /**
     * 获取指定单元最新状态记录
     * 
     * @param unitId 单元ID
     * @return EhsUnitLateststatus
     * @author QuCheng Tech
     * @since 2024/6/28
     */
    public EhsUnitLateststatus getbyUnitId(String unitId) throws QCPromptException {
        if (StringUtils.isBlank(unitId)) throw new QCPromptException("单元ID不能为空");
        return repository.selectById(unitId);
    }

    /**
     * 新增单元最新状态
     * 
     * @param entity
     * @return 成功返回null，失败返回错误或提示信息
     * @author QuCheng Tech
     * @since 2024/7/1
     */
    public String addUnitLatestStatus(EhsUnitLateststatus entity){
        if (entity == null) return QCUnifyReturnValue.Warn("对象不能为空");
        if (StringUtils.isBlank(entity.getUnitid())) return QCUnifyReturnValue.Warn("单元ID不能为空");
        
        if (repository.insert(entity) < 0x1) return QCUnifyReturnValue.Warn("保存失败");
        
        return QCUnifyReturnValue.Success();
    }

    /**
     * 修改单元最新状态
     *
     * @param entity
     * @return 成功返回null，失败返回错误或提示信息
     * @author QuCheng Tech
     * @since 2024/7/1
     */
    public String updateUnitLatestStatus(EhsUnitLateststatus entity){
        if (entity == null) return QCUnifyReturnValue.Warn("对象不能为空");
        if (StringUtils.isBlank(entity.getUnitid())) return QCUnifyReturnValue.Warn("单元ID不能为空");
        
        if (!unitLatestStatusIsExist(entity.getUnitid())) return QCUnifyReturnValue.Warn("单元状态记录不存在");
       
        repository.updateById(entity);
        return QCUnifyReturnValue.Success();
    }

    /**
     * 判断单元状态记录是否存在
     *
     * @param unitId 单元ID
     * @return
     * @author QuCheng Tech
     * @since 2024/7/1
     */
    private boolean unitLatestStatusIsExist(String unitId){
        EhsUnitLateststatus en = repository.selectById(unitId);
        if (Objects.nonNull(en)){
            return true;
        }
        return false;
    }
}
